import React from 'react';
import { isEmpty } from 'lodash';
import { Button,Radio, message, Checkbox, Pagination } from 'antd';
import {WeaTools, WeaLocaleProvider, WeaDialog, WeaInput, WeaInputSearch, WeaNewScroll} from 'ecCom';

const getLabel = WeaLocaleProvider.getLabel;

// 元素设置
class EPortalBrowser extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            visible: false,
            loading: false,
            value: this.props.value,
        };
        this.getButtons = this.getButtons.bind(this);
        this.onLoading = this.onLoading.bind(this);
        this.onOk = this.onOk.bind(this);
        this.onClear = this.onClear.bind(this);
        this.onCancel = this.onCancel.bind(this);
        this.onShow = this.onShow.bind(this);
        this.onChange = this.onChange.bind(this);
    }

    componentWillReceiveProps(nextProps) {
        this.setState({ value: nextProps.value });
    }

    render() {
        const { type, value, tabname, disabled, multiCheck, isShow, title, hasSearch, itemData = [],tabindex } = this.props;
        const { visible, loading } = this.state;
        let displayComp = <div />;

        let replaceValue = '';
        let itemDataName = '';
        if (itemData && !isEmpty(itemData)) {
            itemData.map((item) => {
                if (item.id == value) {
                    itemDataName = item.name;
                }
            });
            replaceValue = itemDataName || value;
        } else {
            replaceValue = tabname || value;
        }

        if (type == 'button') {
            displayComp = <div onClick={this.onShow}>{this.props.children}</div>;
        } else {
            displayComp = <WeaInputSearch ecId={`${this && this.props && this.props.ecId || ''}_WeaInputSearch@1wy850`} style={{ width: '100%', height: '30px', lineHeight: '30px' }} value={getLabel(tabindex,replaceValue) } onSearch={this.onShow} />;
        }

        if (disabled) {
            displayComp = <WeaInput ecId={`${this && this.props && this.props.ecId || ''}_WeaInput@59pct8`} value={getLabel(tabindex,replaceValue)} disabled={true} />;
        }

        let searchhtml=<div/>;
        if(this.props.ebaseid == 'timeLine'){
            searchhtml=<WeaInputSearch  ecId={`${this && this.props && this.props.ecId || ''}_WeaInputSearch@0vxo5o`} style={{ float: 'right', marginRight: '20px' }} placeholder={getLabel(520606, '按样式名称搜索')} onSearch={(value) => { this.refs.ml && this.refs.ml.setNameData(value); this.refs.ml && this.refs.ml.getDatas('1', '10'); }} />
        }else if(this.props.ebaseid == 'MyCalendar'){
            searchhtml=<WeaInputSearch ecId={`${this && this.props && this.props.ecId || ''}_WeaInputSearch@lpygx3`}  style={{ float: 'right', marginRight: '20px' }} placeholder={getLabel(520606, '按样式名称搜索')} onSearch={(value) => { this.refs.ml && this.refs.ml.setNameData(value); this.refs.ml && this.refs.ml.getDatas('1', '10'); }} />
        }else{
            searchhtml=<WeaInputSearch  ecId={`${this && this.props && this.props.ecId || ''}_WeaInputSearch@f6zhd8`} style={{ float: 'right', marginRight: '20px' }} onSearch={(value) => {if (this.refs.ml) {this.refs.ml.setNameData(value);this.refs.ml.getDatas('1', '10');}}}/>
        }

        return (
            <div>
                {displayComp}
                <WeaDialog ecId={`${this && this.props && this.props.ecId || ''}_WeaDialog@hlnboz`}
                  visible={visible}
                  loading={loading}
                  title={title}
                  icon="icon-coms-portal"
                  iconBgcolor="#1a57a0"
                  style={{ width: 800, height: 489 }}
                  zIndex={1050}
                  buttons={this.getButtons()}
                  onCancel={this.onCancel}
                >
                    {
                        hasSearch && <div className={'portal-esetting-browser-search'}>{searchhtml}</div>
                    }
                    <PortalBrowserLib ecId={`${this && this.props && this.props.ecId || ''}_PortalBrowserLib@nf1y9n`} api={this.props.api} ref="ml" hasSearch={hasSearch} multiCheck={multiCheck} onLoading={this.onLoading} isShow={isShow} itemData={itemData} value={value} />
                </WeaDialog>
            </div>
        );
    }

    getButtons() {
        let buttons = [];
        buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@sj7xtz`} type="primary" onClick={this.onOk}>{getLabel(826, '确定')}</Button>);
        // buttons.push(<Button type="primary" onClick={this.onClear}>{getLabel(311, '清除')}</Button>);
        buttons.push(<Button ecId={`${this && this.props && this.props.ecId || ''}_Button@7j0wkx`} type="ghost" onClick={this.onCancel}>{getLabel(31129, '取消')}</Button>);
        return buttons;
    }

    onLoading(loading) {
        this.setState({ loading });
    }

    onShow() {
        this.setState({ visible: true });
        this.refs.ml && this.refs.ml.setVisible({ visible: true });
    }

    onOk() {
        const checkedFiles = this.refs.ml.getCheckedFiles();
        if ((checkedFiles && checkedFiles.length) || this.state.value) {
            if (checkedFiles && checkedFiles.length) {
                const id = checkedFiles.map(item => item.id);
                const name = checkedFiles.map(item => item.name);
                const browsertype = checkedFiles.map(item => item.browsertype);
                if (this.props.ebaseid == 'timeLine') {
                    this.onTimeLineChange(id.join(','), name.join(','), browsertype.join(','), checkedFiles);
                } else if (this.props.ebaseid == 'MyCalendar') {
                    const isdoubleweek = checkedFiles.map(item => item.isdoubleweek);
                    const isdefaultlunar = checkedFiles.map(item => item.defaultlunar);
                    this.onMyCalendarChange(id.join(','), name.join(','), browsertype.join(','),isdoubleweek.join(','),isdefaultlunar.join(','), checkedFiles);
                } else {
                    this.onChange(id.join(','), name.join(','), checkedFiles);
                }
            } else if (this.props.ebaseid == 'timeLine') {
                this.onTimeLineChange(this.state.value, '', checkedFiles);
            } else if (this.props.ebaseid == 'MyCalendar') {
                this.onMyCalendarChange(this.state.value, '', checkedFiles);
            } else {
                this.onChange(this.state.value, '', checkedFiles);
            }

            this.refs.ml.setVisible(false);
            this.setState({ visible: false });
        } else {
            message.warning(getLabel(84570, '请选择目标！'));
        }
    }

    onClear() {
        if (this.props.ebaseid == 'timeLine') {
            this.onTimeLineChange('');
        } else if (this.props.ebaseid == 'MyCalendar') {
            this.onMyCalendarChange('');
        } else {
            this.onChange('');
        }
        this.refs.ml.setVisible(false);
        this.setState({ visible: false, value: '' });
    }

    onCancel() {
        this.refs.ml.setVisible(false);
        this.setState({ visible: false });
    }

    onChange(value, name, datas) {
        this.props.onChange(value, name, datas);
    }
    onTimeLineChange(value, name, datas) {
        this.props.onChange(value, name, datas);
    }
    onMyCalendarChange(value, name, datas,isdoubleweek,isdefaultlunar) {
        this.props.onChange(value, name, datas,isdoubleweek,isdefaultlunar);
    }
}

export default EPortalBrowser;


class PortalBrowserLib extends React.Component {
    searchName = '';

    constructor(props) {
        super(props);
        this.state = { data: this.props.itemData || [], visible: true, hasRight: false, checkedFiles: '', pageCurrent: 1, pageSize: 10, pageTotal: 0 };
        this.setVisible = this.setVisible.bind(this);
        this.onCheck = this.onCheck.bind(this);
        this.getDatas = this.getDatas.bind(this);
        this.onPageCurrentChange = this.onPageCurrentChange.bind(this);
        this.onPageSizeChange = this.onPageSizeChange.bind(this);
    }

    componentWillMount() {
        this.props.api && this.getDatas();
    }

    setNameData = (name) => {
        this.searchName = name;
    }

    onPageCurrentChange(pageCurrent) {
        this.setState({ pageCurrent });
        const { pageSize } = this.state;
        this.getDatas(pageCurrent, pageSize);
    }

    onPageSizeChange(current, pageSize) {
        this.setState({ pageSize });
        this.onPageCurrentChange(1);
        this.getDatas(1, pageSize);
    }

    getDatas(pageCurrent, pageSize) {
        this.props.onLoading(true);
        const { api } = this.props;
        WeaTools.callApi(api, 'GET', {
            pageCurrent: pageCurrent || this.state.pageCurrent,
            pageSize: pageSize || this.state.pageSize,
            name: this.searchName,
        }).then((result) => {
            this.setState({
                data: result.datas,
                pageTotal: result.count,
                checkedFiles: [],
                edit: false,
                file: {},
            });
            this.props.onLoading(false);
        });
    }

    onCheck(file) {
        const { multiCheck = false } = this.props;
        let { checkedFiles } = this.state;

        if (_.findIndex(checkedFiles, item => item.id == file.id) != -1) {
            _.remove(checkedFiles, item => item.id == file.id);
        } else if (multiCheck) {
                checkedFiles.push(file);
            } else {
                checkedFiles = [file];
            }

        this.setState({ checkedFiles });
    }

    render() {
        const { value, hasSearch } = this.props;
        const { visible, pageCurrent, pageSize, pageTotal, data = [] } = this.state;
        const { checkedFiles } = this.state;
        let valuenew = value;
        let row = [],
        col = [];
        for (let i = 0, len = data.length; i < len; i++) {
            col.push(data[i]);
            if (value == data[i].name && value != data[i].id) {
                valuenew = data[i].id;
            }
            if (i % 5 == 4 || i == len - 1) {
                row.push(col);
                col = [];
            }
        }

        let style = {};
        if(this.props.api){
            style = {paddingBottom:'50px'};
        }
        if (hasSearch) {
            style = {
                height: '92%',
            };
        }
        if(this.props.api && hasSearch){
            style = {
                height: '92%',paddingBottom:'50px'
            };
        };

        if (visible) {
            return (
                <div className="portal-esetting-browser" style={style}>
                    {
                        row && row.length ? (
                            <div style={{height:'100%'}}>
                                <WeaNewScroll  height="100%">
                                    <div className="portal-esetting-browser-middle">
                                                <div className="portal-esetting-browser-table">
                                                    {
                                                        row.map((row, index) => (
                                                                <ul key={index} className="portal-esetting-browser-tr">
                                                                    {
                                                                        row.map((col) => {
                                                                            let checked = _.findIndex(checkedFiles, item => item.id == col.id) != -1;
                                                                            if (isEmpty(checkedFiles)) {
                                                                                checked = col.id == valuenew;
                                                                            }
                                                                            return (
                                                                                <li key={col.id} className="portal-esetting-browser-td">
                                                                                    <div className="portal-esetting-browser-item" style={checked ? { border: '1px solid #408de2' } : {}} >
                                                                                        <div title={col.name} className="portal-esetting-browser-chk" onClick={() => this.onCheck(col)}><Radio ecId={`${this && this.props && this.props.ecId || ''}_Checkbox@udryw2@${col.id}`} checked={checked} />&nbsp;&nbsp;{col.name}</div>
                                                                                        <div className="portal-esetting-browser-preview">
                                                                                            <img className="portal-esetting-browser-img" src={col.filepath} alt="" />
                                                                                        </div>
                                                                                    </div>
                                                                                </li>
                                                                            );
                                                                        })
                                                                    }
                                                                </ul>
                                                            ))
                                                    }
                                            </div>
                                        </div>
                                    </WeaNewScroll>
                                    {
                                        this.props.api && <div style={{ position: 'absolute', right: 0, margin: '10px',bottom:'0px' }}>
                                            <Pagination ecId={`${this && this.props && this.props.ecId || ''}_Pagination@6dysuz`}
                                              showSizeChanger
                                              showQuickJumper
                                              current={pageCurrent}
                                              pageSize={pageSize}
                                              total={pageTotal}
                                              showTotal={total => `${getLabel(18609, '共')} ${total} ${getLabel(18256, '条')}`}
                                              pageSizeOptions={['10', '20', '50', '100']}
                                              onChange={this.onPageCurrentChange}
                                              onShowSizeChange={this.onPageSizeChange}
                                            />
                                        </div>
                                    }
                                </div>
                            ) : (
                                <div className="ant-table-placeholder">
                                    <i className="anticon anticon-frown" />{getLabel(83553, '暂无数据')}
                            </div>
                            )
                            }
                        </div>
            );
        }
            return '';
    }

    setVisible(visible) {
        this.setState({ visible });
    }

    getCheckedFiles() {
        return this.state.checkedFiles;
    }
}
